<template>
  <Form ref="formCom" :validation-schema="myschema" autocomplete="off" v-slot="{errors}" class="bottom">
                <div class="mobile">
                  <i class="icon iconfont icon-user"></i>
                  <Field :class="{active:errors.account}" name="account" v-model="form.account" type="text" placeholder="请输入用户名" />
                  <span v-if="errors.account">{{errors.account}}</span>
              </div>
               <div class="mobile">
                  <i class="icon iconfont icon-phone"></i>
                  <Field :class="{active:errors.mobile}" name="mobile" v-model="form.mobile" type="text" placeholder="请输入手机号" />
                  <span v-if="errors.mobile">{{errors.mobile}}</span>
              </div>
              <div class="mobile">
                  <i class="icon iconfont icon-code"></i>
                  <Field type="text" :class="{active:errors.code}" name="code" v-model="form.code" placeholder="请输入验证码" />
                  <span v-if="errors.code">{{errors.code}}</span>
                  <em @click="send">{{time <= 0 ?  '发送验证码':`${time}秒后发送`}}</em>
              </div>
              <div class="mobile">
                  <i class="icon iconfont icon-lock"></i>
                  <Field :class="{active:errors.password}" name="password" v-model="form.password" type="password" placeholder="请输入密码" />
                  <span v-if="errors.password">{{errors.password}}</span>
              </div> <div class="mobile">
                  <i class="icon iconfont icon-lock"></i>
                  <Field  type="password" name="rePassword" :class="{active:errors.rePassword}" v-model="form.rePassword" placeholder="请输入密码" />
                  <span v-if="errors.rePassword">{{errors.rePassword}}</span>
              </div>
              <a href="javascript:;" @click="submit">立即提交</a>
          </Form>
</template>

<script>
import { Form, Field } from 'vee-validate'
import { reactive } from 'vue-demi'
import { ref, onUnmounted } from 'vue'
import schema from '@/utils/vee-validate-schema'
import { useIntervalFn } from '@vueuse/core'
import Message from '@/components/libaray/Message'
import { userQQPatchCode, userPatch } from '@/api/user'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  naem: 'CallbackPitch',
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  components: {
    Form, Field
  },
  setup (props) {
    // 1.表单校验 多两个校验:用户名是否存在，再次输入密码是否一致
    // 2.发送短信验证码,发送的接口API定义
    // 3.完善信息
    const formCom = ref(null)
    const form = reactive({
      account: null,
      mobile: null,
      code: null,
      password: null,
      rePassword: null
    })
    const myschema = {
      account: schema.accountApi,
      mobile: schema.mobile,
      code: schema.code,
      password: schema.password,
      rePassword: schema.rePassword
    }

    // -------------------------------------

    // 发送短信验证码
    // pause暂停，resume开始

    const time = ref(0)
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000, { immediate: false })
    // 发送短信
    onUnmounted(() => {
      pause()
    })
    const send = async () => {
      const valid = myschema.mobile(form.mobile)
      if (valid === true) {
        // 通过
        // 没有倒计时才可以发送请求
        if (time.value === 0) {
          try {
            await userQQPatchCode(form.mobile)
            Message({ type: 'success', message: '发送成功' })
            time.value = 60
            resume()
          } catch (err) {
            Message({ type: 'error', message: '用户不存在' })
          }
        }
      } else {
        // 失败,使用vee的错误函数显示错误信息 setFieldError(字段名称,错误信息)
        formCom.value.setFieldError('mobile', valid)
      }
    }
    // ---------------------------------

    // 完善信息
    const store = useStore()
    const router = useRouter()
    const submit = async () => {
      const valid = formCom.value.validate()
      if (valid) {
        userPatch(props.unionId, form).then(data => {
        // 绑定成功
        // 实现和之前登录一样的逻辑
          const { id, account, avatar, mobile, nickname, token } = data.result
          store.commit('user/setUser', { id, account, avatar, mobile, nickname, token })

          store.dispatch('cart/mergeCart').then(() => {
            router.push(store.state.user.redirectUrl)
            Message({ type: 'success', message: 'QQ完善成功' })
          })
        }).catch(error => {
          console.log(error)

          Message({ type: 'error', message: 'QQ完善失败' })
        })
      }
    }

    return { Form, Field, form, myschema, formCom, send, time, submit }
  }
}
</script>

<style scoped lang="less">
.bottom {
        padding-top: 30px;
        a {
            display: block;
            width: 320px;
            height: 50px;
            background-color: @xtxColor;
            line-height: 50px;
            text-align: center;
            color: #fff;
            border-radius: 4px;
        }
        .shang {
            img {
                width: 50px;
                height: 50px;
            }
            display: flex;
            align-items: center;
            width: 320px;
            height: 70px;
            background: #f2f2f2;
            padding: 8px 8px;
            span {
                padding-left: 10px;
            }
        }
        .mobile {
            width: 320px;
            height: 50px;
            position: relative;
            margin: 30px 0;
            input {
                width: 100%;
                height: 100%;
                border: 1px solid #ccc;
                padding-left: 35px;
                &.active {
                    border-color: red;
                }
                &:focus {
                    border-color: @xtxColor;
                }
            }
            i {
                position: absolute;
                top: 14px;
                left: 10px;
                font-size: 16px;
                color: #999;
            }
            span {
                position: absolute;
                left: 330px;
                width: 180px;
                top:15px;
                color: red;
            }
            em {
                position: absolute;
                font-style: normal;
                top: 15px;
                right: 10px;
                color: #999;
                cursor: pointer;
            }
        }
    }
</style>
